package com.hyperf.core.bean.result;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.hyperf.core.exception.CustomException;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * @author lizhaoyang
 */
@Getter
@Setter
@NoArgsConstructor
public class PageResult<T> implements Serializable {

    private static final long serialVersionUID = 9202058449799170385L;

    private static final int EMPTY_PAGE_TOTAL = 0;

    /**
     * 当前页码
     */
    private int page;

    /**
     * 每页条数
     */
    private int pageSize;

    /**
     * 总页数
     */
    private int totalPage;

    /**
     * 总条数
     */
    private int total;

    /**
     * 数据列表
     */
    private List<T> list;

    public PageResult(int page, int pageSize, int total, List<T> list) {
        this.page = page;
        this.pageSize = pageSize;
        this.total = total;
        this.totalPage = NumberUtil.ceilDiv(total, pageSize);
        this.list = list;
    }

    /**
     * 功能:封装分页结果集
     *
     * @param page
     * @param pageSize
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildResult(int page, int pageSize) {
        return buildResult(page, pageSize, EMPTY_PAGE_TOTAL, Collections.emptyList());
    }

    /**
     * 功能:封装分页结果集
     *
     * @param page
     * @param pageSize
     * @param <R>
     * @return
     */
    public static <R> PageResult<R> buildResult(int page, int pageSize, int total, List<R> data) {
        if (pageSize <= 0) {
            throw new CustomException("pageSize cannot be less than or equal to 0");
        }
        return new PageResult<>(page, pageSize, total, data);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
